<script setup>
import {onMounted, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import http from "@/request/http.js";
import {useRoute} from "vue-router";

const route = useRoute();

// 文章列表数据
const articleList = ref([]);
const selectedArticleIds = ref([]); // 多选选中的文章ID
const isLoading = ref(false); // 加载状态

// 搜索表单（状态筛选使用statusId参数）
const searchForm = ref({
  title: '',
  username: '',
  categoryName: '',
  userId: null,
  statusId: null,
});

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0
});

// 批量操作相关
const batchBanDialogVisible = ref(false);
const batchUnbanDialogVisible = ref(false);
const batchBanForm = ref({
  articleIds: [],
  userIds: [], // 作者ID列表
  banReason: '',
  banType: 'SYSTEM_BAN'
});
const batchUnbanForm = ref({
  articleIds: [],
  userIds: [],
  unbanReason: ''
});

// 时间格式化
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr.replace('T', ' '));
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedArticleIds.value = selection.map(item => item.articleId);
};

// 状态下拉框变化事件
const handleStatusChange = () => {
  // 重置到第一页
  pagination.value.currentPage = 1;
  handleSearch();
};

// 清除状态筛选
const clearStatusFilter = () => {
  searchForm.value.statusId = '';
  handleSearch();
};

// 获取文章列表
const handleSearch = async () => {
  try {
    isLoading.value = true;
    const params = {
      currentPage: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      title: searchForm.value.title,
      username: searchForm.value.username,
      categoryName: searchForm.value.categoryName,
      userId: searchForm.value.userId,
      statusId: searchForm.value.statusId || undefined
    };

    // 移除空参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    const response = await http.get('/article/getList', {params});
    if (response.code === 200) {
      articleList.value = response.data.records || [];
      pagination.value = {
        ...pagination.value,
        total: response.data.total || 0,
        pages: response.data.pages || 0
      };
    } else {
      ElMessage.error('获取数据失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('网络错误，无法加载文章列表');
    console.error('文章列表请求异常：', error);
  } finally {
    isLoading.value = false;
  }
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    title: '',
    username: '',
    categoryName: '',
    userId: null,
    statusId: ''
  };
  pagination.value.currentPage = 1;
  handleSearch();
};

// 打开批量封禁对话框
const openBatchBanDialog = () => {
  if (selectedArticleIds.value.length === 0) {
    ElMessage.warning('请先选择要封禁的文章');
    return;
  }

  // 检查选中的是否都是正常文章
  const selectedArticles = articleList.value.filter(a =>
      selectedArticleIds.value.includes(a.articleId)
  );

  const hasBanned = selectedArticles.some(a => a.articleStatusId === '2');
  if (hasBanned) {
    ElMessage.warning('选中的文章中包含已封禁文章，请只选择正常状态的文章');
    return;
  }

  // 提取选中文章的作者ID
  const userIds = selectedArticles.map(article => article.userId).filter(Boolean);

  batchBanForm.value = {
    articleIds: [...selectedArticleIds.value],
    userIds: userIds,
    banReason: '',
    banType: 'SYSTEM_BAN'
  };
  batchBanDialogVisible.value = true;
};

// 打开批量解封对话框
const openBatchUnbanDialog = () => {
  if (selectedArticleIds.value.length === 0) {
    ElMessage.warning('请先选择要解封的文章');
    return;
  }

  // 检查选中的是否都是封禁文章
  const selectedArticles = articleList.value.filter(a =>
      selectedArticleIds.value.includes(a.articleId)
  );

  const hasNormal = selectedArticles.some(a => a.articleStatusId === '1');
  if (hasNormal) {
    ElMessage.warning('选中的文章中包含正常文章，请只选择已封禁的文章');
    return;
  }

  // 提取选中文章的作者ID
  const userIds = selectedArticles.map(article => article.userId).filter(Boolean);

  batchUnbanForm.value = {
    articleIds: [...selectedArticleIds.value],
    userIds: userIds,
    unbanReason: ''
  };
  batchUnbanDialogVisible.value = true;
};

// 确认批量封禁
const confirmBatchBan = async () => {
  if (!batchBanForm.value.banReason) {
    ElMessage.warning('请输入封禁原因');
    return;
  }

  try {
    isLoading.value = true;
    const banData = {
      articleIdList: batchBanForm.value.articleIds,
      articleBanReason: batchBanForm.value.banReason,
      articleBanType: batchBanForm.value.banType,
      userIds: batchBanForm.value.userIds
    };

    const response = await http.put('/system/articleBan/banArticles', banData);

    if (response.code === 200) {
      ElMessage.success('批量封禁成功');
      batchBanDialogVisible.value = false;
      selectedArticleIds.value = [];
      handleSearch(); // 刷新列表
    } else {
      ElMessage.error(`封禁失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error('网络错误，批量封禁操作失败');
  } finally {
    isLoading.value = false;
  }
};

// 确认批量解封
const confirmBatchUnban = async () => {
  if (!batchUnbanForm.value.unbanReason) {
    ElMessage.warning('请输入解封原因');
    return;
  }

  try {
    isLoading.value = true;
    const unbanData = {
      articleIds: batchUnbanForm.value.articleIds,
      unbanReason: batchUnbanForm.value.unbanReason,
      userIds: batchUnbanForm.value.userIds
    };

    const response = await http.put('/system/articleBan/unbanArticles', unbanData);

    if (response.code === 200) {
      ElMessage.success('批量解封成功');
      batchUnbanDialogVisible.value = false;
      selectedArticleIds.value = [];
      handleSearch(); // 刷新列表
    } else {
      ElMessage.error(`解封失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error('网络错误，批量解封操作失败');
  } finally {
    isLoading.value = false;
  }
};

// 分页相关
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1;
  handleSearch();
};

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  handleSearch();
};

// 关闭对话框
const closeBatchBanDialog = () => {
  batchBanDialogVisible.value = false;
};

const closeBatchUnbanDialog = () => {
  batchUnbanDialogVisible.value = false;
};

// 路由变化时刷新数据
watch(
    () => route.fullPath,
    () => {
      handleSearch();
    }
);

// 初始化加载数据
onMounted(() => {
  handleSearch();
});
</script>

<template>
  <div class="article-container">
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="文章标题">
          <el-input
              v-model="searchForm.title"
              clearable
              placeholder="请输入标题关键词"
              style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="作者账号">
          <el-input
              v-model="searchForm.username"
              clearable
              placeholder="请输入作者账号"
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="所属分类">
          <el-input
              v-model="searchForm.categoryName"
              clearable
              placeholder="未分类可不填"
              style="width: 180px"
          />
        </el-form-item>

        <!-- 状态筛选下拉选项 -->
        <el-form-item label="文章状态">
          <el-select
              v-model="searchForm.statusId"
              :loading="isLoading"
              clearable
              placeholder="请选择状态"
              style="width: 150px"
              @change="handleStatusChange"
          >
            <el-option label="全部" value=""/>
            <el-option label="正常" value="1"/>
            <el-option label="已封禁" value="2"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button :loading="isLoading" type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operation-buttons">
      <el-button
          type="danger"
          :disabled="selectedArticleIds.length === 0"
          @click="openBatchBanDialog"
      >
        封禁选中文章
      </el-button>
      <el-button
          :disabled="selectedArticleIds.length === 0"
          style="margin-left: 10px"
          type="success"
          @click="openBatchUnbanDialog"
      >
        解封选中文章
      </el-button>
    </div>

    <el-table
        :data="articleList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="isLoading"
        element-loading-text="加载中..."
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" label="序号" width="80">
        <template #default="scope">
          {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="280">
        <template #default="scope">
          <div :title="scope.row?.title" class="title-ellipsis">{{ scope.row?.title || '无标题' }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="作者" prop="username" width="120"/>
      <el-table-column align="center" label="分类" width="140">
        <template #default="scope">
          <el-tag v-if="scope.row?.category && scope.row.category.length" class="category-tag" type="info">
            {{ scope.row.category.join('、') }}
          </el-tag>
          <span v-else class="empty-tag">未分类</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布时间" width="180">
        <template #default="scope">
          {{ scope.row?.publishTime ? formatTime(scope.row.publishTime) : '未发布' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row?.articleStatusId === '1'" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row?.articleStatusId === '2'" type="danger">已封禁</el-tag>
          <el-tag v-else type="warning">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="点赞数" prop="likeCount" width="80"/>
      <el-table-column align="center" label="评论数" prop="commentCount" width="80"/>
    </el-table>

    <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 批量封禁对话框 -->
    <el-dialog
        v-model="batchBanDialogVisible"
        :before-close="closeBatchBanDialog"
        :close-on-click-modal="false"
        title="批量文章封禁"
        width="500px"
    >
      <el-form :model="batchBanForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item disabled label="文章ID列表">
          <div class="id-display-container">
            <el-tag
                v-for="id in batchBanForm.articleIds"
                :key="id"
                class="id-tag"
                type="default"
            >
              {{ id }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="封禁类型">
          <el-select v-model="batchBanForm.banType" placeholder="请选择封禁类型">
            <el-option label="系统封禁" value="SYSTEM_BAN"/>
            <el-option label="违规封禁" value="VIOLATION_BAN"/>
            <el-option label="版权封禁" value="COPYRIGHT_BAN"/>
          </el-select>
        </el-form-item>
        <el-form-item label="封禁原因" required>
          <el-input
              v-model="batchBanForm.banReason"
              placeholder="请输入封禁原因"
              rows="4"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeBatchBanDialog">取消</el-button>
        <el-button type="primary" @click="confirmBatchBan">确认批量封禁</el-button>
      </template>
    </el-dialog>

    <!-- 批量解封对话框 -->
    <el-dialog
        v-model="batchUnbanDialogVisible"
        :before-close="closeBatchUnbanDialog"
        :close-on-click-modal="false"
        title="批量文章解封"
        width="500px"
    >
      <el-form :model="batchUnbanForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item disabled label="文章ID列表">
          <div class="id-display-container">
            <el-tag
                v-for="id in batchUnbanForm.articleIds"
                :key="id"
                class="id-tag"
                type="default"
            >
              {{ id }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="解封原因" required>
          <el-input
              v-model="batchUnbanForm.unbanReason"
              placeholder="请输入解封原因"
              rows="4"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeBatchUnbanDialog">取消</el-button>
        <el-button type="primary" @click="confirmBatchUnban">确认批量解封</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.article-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 150px);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

/* 筛选标签样式 */
.filter-tag {
  margin: 0 0 15px 0;
  padding: 8px 10px;
  background-color: #f0f2f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-tag :deep(.el-tag) {
  cursor: default;
}

.filter-tag :deep(.el-button) {
  color: #606266;
  padding: 0;
  height: auto;
}

.filter-tag :deep(.el-button):hover {
  color: #409eff;
}

.operation-buttons {
  margin-bottom: 20px;
}

.title-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.empty-tag {
  color: #999;
  font-size: 12px;
}

.id-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 34px;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}

.id-tag {
  background-color: #f5f7fa;
  color: #4e5969;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  padding: 2px 10px;
  font-size: 14px;
  height: auto;
  line-height: 1.5;
}

.category-tag {
  background-color: #f5f7fa;
  color: #4e5969;
  border: 1px solid #e5e6eb;
}

:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

/* 加载状态样式 */
:deep(.el-select .el-input__wrapper.is-loading) {
  opacity: 0.7;
  pointer-events: none;
}
</style>